<?php
/**
 * Created by PhpStorm.
 * User: 戎大富
 * Date: 2019/9/6
 * Time: 16:21
 */
namespace app\admin\controller;
use think\Db;
use think\Loader;
use tixian\WX\Weixin;
use tixian\WX\Ali;

class Withdraw extends Base {
    // 微信提现配置
    public $wx_config = [
        'key' => 'wVNAxT3I8dJl1nabp2t6KfNt0ufvurr4', // 商户平台设置的秘钥
        'mch_appid' => 'wx1ddf922fb0cd6ca7', // 商户号的appid
        'mchid' => '1557073621' // 商户号
    ];
    
    // 支付宝提现配置 rsaPrivateKey:私钥  alipayrsaPublicKey:支付宝生成的支付宝公钥
    public $ali_config = [
        'appId' => '2019092467788171',
        'rsaPrivateKey' => 'MIIEogIBAAKCAQEAqU+7LibJfa6+0sR/XZZjOw0VwwJxngHpG4t7lnYyo00p5tlz4R4PaasyUm1OfoNYzVJJjorRcipTobmmqk1KFzyTZdRlLFC+PItq2Mw+oXxYkrqUi0r21zncXo0yiv1bGrTdqAxMgZOWHzWSPZhLpz7VPQck4EVqHesSb9GGGalHO+rrtQC9/aJfeIzGb+MCwgdNdfzycOh25cPeDGfDe2pXnkCmFw+UCGpz+bqGnrMKdvv/Vay8Nvy0CdJTYYzjH7srowRrbJ82uW75qUggiH993RsEhXnK/FAbC0wXwjormlrCQf3gyMSLO35+1BPw0SH7LNIza95DjOj+F9VUbwIDAQABAoIBACQfLJIWGFrGE1QoM/wlf5ozmnb2aIMLaU5FHeLl6LvKVKw5rG1U2njy21OWmm6HW0TCz4qntzOiMCGK2DHxN2NpuxC4lbU0rMGCBROnz5zoSIVVZSeqoKseXxOVEDlzACLcf4XAyfnDIP4bkc2uVkWiNCBHC+kFJjSn2FEe5HtItzQ+Q7s4Bht4dpop4mi7fZ7ePdgIQ5+aJZ+crj4zAfIyuxUZpQKOQFZS8C3XUT1JSAtBYyx7nVXVzWGquu32oVS2nlFnuXajdMsFfIiak8Y4ngXdMd+ot9FLg9c2RjfantFbudtLY8It9Nf0f2NmeJCutr2sUE5Tt1xAWZtBQyECg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n1jdDSSkI2iNAzn7nRBq9lnOPiJ3+x0KcEpM87CYbR26zuRueqc1mJ/UnzcgVrqMy4PDsCWOynC39deZtaQFtvv0EGvhg3aIgQaeOFybx52J/flSu0+7XQpTlzaivuSjv5JZzHHgeetGXXsQM+7UXbQZ4B0/E37tv/i/b3Gzg4YnDEwvNsNqdYAemABQIDAQAB'
    ];
    
    public function index(){
        if(request()->isAjax()){
            extract(input());
            $map =array();
            $page = input('page') ? input('page'):1;
            $limit = input("limit")?input("limit"):10;// 获取总条数;
            if(isset($keyword)&&$keyword!="")
            {
                $map['uuu.user_username|uuu.user_phone'] = ['like',"%" . $keyword . "%"];
            }
            if(isset($withdraw_status)&&$withdraw_status!="")
            {
                $map['withdraw_status'] = $withdraw_status;
            }
            if(isset($start)&&$start!=""&&isset($end)&&$end=="")
            {
                $map['a.withdraw_create_time'] = ['>= time',$start];
            }
            if(isset($end)&&$end!=""&&isset($start)&&$start=="")
            {
                $map['a.withdraw_create_time'] = ['<= time',$end];
            }
            if(isset($start)&&$start!=""&&isset($end)&&$end!="")
            {
                $map['a.withdraw_create_time'] = ['between time',[$start,$end]];
            }

            $count = Db::table('up_withdraw')->alias('a')
                ->join('up_u_user uuu','uuu.user_id = a.withdraw_user_id','left')
                ->where($map)
                ->count();
            $list = Db::table('up_withdraw')->alias('a')
                ->join('up_u_user uuu','uuu.user_id = a.withdraw_user_id','left')
                ->where($map)
                ->field('uuu.user_username,uuu.user_phone,uuu.user_id,a.*')
                ->order('withdraw_create_time desc')
                ->page($page, $limit)
                ->select();//计算总页面

            return json(['code'=>220,'msg'=>'','count'=>$count,'data'=>$list]);
        }
        return $this->fetch();
    }
    
    /**
     * 通过
     * @return \think\response\Json
     */
    public function adopt(){
        $ids = input('id');
        $info = Db::table('up_withdraw')->where('withdraw_id', $ids)->find();
        // 提现手续费
        $dis = Db::table('up_about')->where('about_id', 14)->value('about_tixian_dis');
        $ratio = 100 - $dis;
        $price = $info['withdraw_money'] * $ratio * 0.01; // 实际到账金额
        
        // todo:1 调取微信/支付宝提现接口  2 提现成功修改提现申请状态  3 提现成功参入到order表  4 减用户余额
        if($info['withdraw_type'] == 1){
            Loader::import('tixian.Weixin',EXTEND_PATH,'.php');
            $wxtx = new Weixin($this->wx_config);
            $res = $wxtx->wxTiXian($info['withdraw_num'], $info['withdraw_openid'], $info['withdraw_rel_name'], $price);
            $return_code = (string)$res->return_code;
            $result_code = (string)$res->result_code;
            $return_code = trim(strtoupper($return_code));
            $result_code = trim(strtoupper($result_code));
            if($return_code == 'SUCCESS' && $result_code == 'SUCCESS'){
                $success = 1;
            }else{
               $success = 0;
               $msg = (string)$res->return_msg;
            }
        }else{ // 支付宝
            $data = [
                'out_biz_no' => $info['withdraw_num'], // 订单号
                'payee_account' => $info['withdraw_zh'], // 支付宝账号
                'amount' => $price, // 交易金额
                'payee_real_name' => $info['withdraw_rel_name'] // 真实姓名
            ];
            Loader::import('tixian.Ali',EXTEND_PATH,'.php');
            $ali = new Ali($this->ali_config);
            $request = $ali->aliTiXian($data);
            if($request['code'] == 1){
                $success = 1;
            }else{
                $success = 0;
                // $result->$responseNode->sub_msg 这个参数 是返回的错误信息
                $msg = $request['msg'];
            }
        }
        
        if($success == 1){
            // 我的信息
            $user_info = Db::table('up_u_user')
                ->field('user_invite_code')
                ->where('user_id', $info['withdraw_user_id'])
                ->find();
            Db::startTrans();
            try{
                // 修改提现订单状态和审核时间
                Db::table('up_withdraw')
                    ->where('withdraw_id', $info['withdraw_id'])
                    ->update([
                        'withdraw_status' => 2,
                        'withdraw_att_time' => date('Y-m-d H:i:s')
                    ]);
        
                // 插入Order表
                $order = [
                    'order_type' => 5,
                    'order_price' => $info['withdraw_money'],
                    'order_time' => date('Y-m-d H:i:s'),
                    'order_user_id' => $info['withdraw_user_id'],
                ];
                Db::table('up_order')->insert($order);
        
                //========= 教师收益
                if(!empty($user_info['user_invite_code'])){
                    // 邀请我的老师
                    $invite_me_teacher = Db::table('up_u_user')
                        ->field('user_id, user_status')
                        ->where('user_my_code', $user_info['user_invite_code'])
                        ->find();
                    $allow = [1, 2, 3, 6];
                    if($invite_me_teacher && in_array($invite_me_teacher['user_status'], $allow)){
                        // 收益比例
                        $rebates = Db::table('up_about')->where('about_id', 15)->value('about_rebates');
                        // 收益金额
                        $rebates = $info['withdraw_money'] * $rebates * 0.01;
                
                        // 增加邀请老师的余额
                        Db::table('up_u_user')
                            ->where('user_id', $invite_me_teacher['user_id'])
                            ->setInc('user_balance', $rebates);
                        // 插入收益表
                        $ear = [
                            'ear_invite_user_id' => $invite_me_teacher['user_id'],
                            'ear_by_invite_user_id' => $info['withdraw_user_id'],
                            'ear_num' => $rebates,
                            'ear_time' => date('Y-m-d H:i:s')
                        ];
                        Db::table('up_ear')->insert($ear);
                    }
                }
        
                Db::commit();
                return json(['code' => 200, 'msg' => '操作成功']);
            }catch(\Exception $e){
                Db::rollback();
                return json(['code' => 100, 'msg' => '操作数据库失败']);
            }
        }else{
           return json(['code' => 100, 'msg' => $msg]);
        }
    }
    
    //=============================  支付宝提现   start  ======================//
    /**
     * 支付宝提现
     * @param $info
     * @return \think\response\Json
     */
//    public function aliTiXian($info){
//        header("Content-type: text/html; charset=utf-8");
//        $amount = $info['withdraw_money']; // 提现金额
//        $real_name = $info['withdraw_rel_name']; // 真实姓名
//        $account = $info['withdraw_zh']; // 支付宝账号
//        $order_num = $info['withdraw_num']; // 订单编号
//        // 提现手续费
//        $dis = Db::table('up_about')->where('about_id', 14)->value('about_tixian_dis');
//        $ratio = 100 - $dis;
//        $price = $amount * $ratio * 0.01; // 实际到账金额
//        // 引入文件
//        // require_once(EXTEND_PATH.'alipay/AopSdk.php');
//        Loader::import('alipay.aop.AopClient',EXTEND_PATH,'.php');
//        Loader::import('alipay.aop.request.AlipayFundTransToaccountTransferRequest',EXTEND_PATH,'.php');
//        // Loader::import('alipay.aop.SignData',EXTEND_PATH,'.php');// 在AopClient类中已经引用，此处无序重复引用
//        $aop = new \AopClient();
//        // 支付宝网关，固定不变
//        $aop->gatewayUrl = 'https://openapi.alipay.com/gateway.do';
//        // appId 应用的ID
//        $aop->appId = '2019092467788171';
//        // 私钥，工具生成
//        $aop->rsaPrivateKey = 'MIIEogIBAAKCAQEAqU+7LibJfa6+0sR/XZZjOw0VwwJxngHpG4t7lnYyo00p5tlz4R4PaasyUm1OfoNYzVJJjorRcipTobmmqk1KFzyTZdRlLFC+PItq2Mw+oXxYkrqUi0r21zncXo0yiv1bGrTdqAxMgZOWHzWSPZhLpz7VPQck4EVqHesSb9GGGalHO+rrtQC9/aJfeIzGb+MCwgdNdfzycOh25cPeDGfDe2pXnkCmFw+UCGpz+bqGnrMKdvv/Vay8Nvy0CdJTYYzjH7srowRrbJ82uW75qUggiH993RsEhXnK/FAbC0wXwjormlrCQf3gyMSLO35+1BPw0SH7LNIza95DjOj+F9VUbwIDAQABAoIBACQfLJIWGFrGE1QoM/wlf5ozmnb2aIMLaU5FHeLl6LvKVKw5rG1U2njy21OWmm6HW0TCz4qntzOiMCGK2DHxN2NpuxC4lbU0rMGCBROnz5zoSIVVZSeqoKseXxOVEDlzACLcf4XAyfnDIP4bkc2uVkWiNCBHC+kFJjSn2FEe5HtItzQ+Q7s4Bht4dpop4mi7fZ7ePdgIQ5+aJZ+crj4zAfIyuxUZpQKOQFZS8C3XUT1JSAtBYyx7nVXVzWGquu32oVS2nlFnuXajdMsFfIiak8Y4ngXdMd+ot9FLg9c2RjfantFbudtLY8It9Nf0f2NmeJCutr2sUE5Tt1xAWZtBQyECgYEA3ds2aVxc/PDBi8rnDzwIyk+rH6CeDTfDPeZbc28+Q8xjpKzwv3vWyb7gPCco/h7/PoPqpMT8+OEpyRGKJDKwmph94Aqf6lnfZseElRbYqNVm72YT8/Rfli0paRRS2hUnqIFgU6HxYaeorFvkIkccHmE+50TumRf86vXshR5RqCkCgYEAw15Vqu3T9NaQAiweZlZsEMhFBeoO4+hLwm5t/DFoVV4DfV9ygNb/LESStE+qojsIeI8u0uVe6aX2A0H01GSf4C1zp6deaNycOsCfOSQMATlea48G7EyBTAZrs0UKyqesjcpijYyU4Zq5Yntj4pzmUapOhurfWwClXuOGMocjitcCgYA3xJTm4zrUskhUtYpjf/nNsT0Y1C0msW+4raErYTlLnaMmj/psh9q0F/ER7d4WEwCiXFKtXH8iqKbyTiBlfQB7u/1YRhNwu2q20Ux4laecuRgI8aXuWu10OKICMgOpoku3xd3K6BhfLd/ug6LTIwDkehlv1RoNDcSb43my9K4eEQKBgFyYGDgj8gInsycka+AK87rcgEI2VYpU7ZsgJYaSkCVtom/ITgecXmJHudQ1seSj3/brvcB8r4hDfR68IuKLMm7Ye+ko3QkMDguWgaBeYkYuP37w0dIqzFkQ7fiQL3YvFAw7sIvv5hwq7dQsMQIVZN+tvPwa03NZEgewBElsXT8PAoGAFPDwhZJCs841y5RIgQv7zgyFNOFLG62RrtuyPQtwSmXn63qJ5s+nC/q0CSnf6Aa+S+btKXk4scjBD5jH6x+EVcPBW43Re23VXRkFIX/+cFHnFoIKXBAAeUm2cuIM1GUspJ3Qi3uYAOzKduk0aAyXQbYskgjaoQNCjEQxhTM+NOE=';
//        // 支付宝公钥 上传应用公钥后 支付宝生成的支付宝公钥
//        $aop->alipayrsaPublicKey = 'MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAridPYBgISD0wFaGZWKqecTCyB0gU737HHin/8ix+HDaErTHt08tXNKRF5aPaZkj/8gJDOU2WgU0iUt7D4fUU3qR5yPqRppE7m08wQvN4bk0LpNotYKCN4Gmd5FtJUkwYw/IwhZ5dhMxSr8OP9ciGkIOvsMn1jdDSSkI2iNAzn7nRBq9lnOPiJ3+x0KcEpM87CYbR26zuRueqc1mJ/UnzcgVrqMy4PDsCWOynC39deZtaQFtvv0EGvhg3aIgQaeOFybx52J/flSu0+7XQpTlzaivuSjv5JZzHHgeetGXXsQM+7UXbQZ4B0/E37tv/i/b3Gzg4YnDEwvNsNqdYAemABQIDAQAB';
//        // 版本  固定
//        $aop->apiVersion = '1.0';
//        // 签名类型  固定
//        $aop->signType = 'RSA2';
//        // 编码  固定
//        $aop->postCharset = 'UTF-8';
//        // 格式 固定
//        $aop->format = 'json';
//        $request = new \AlipayFundTransToaccountTransferRequest();
//        // 收款方账户类型为（payee_type）：
//        // 1.ALIPAY_LOGONID：支付宝登录号，支持邮箱和手机号格式。
//        // 2.ALIPAY_USERID：支付宝账号对应的支付宝唯一用户号。以2088开头的16位纯数字组成。
//        $request->setBizContent("{" .
//            "\"out_biz_no\":\"$order_num\"," .
//            "\"payee_type\":\"ALIPAY_LOGONID\"," .
//            "\"payee_account\":\"$account\"," .
//            "\"amount\":\"$price\"," .
//            "\"payee_real_name\":\"$real_name\"," .
//            "}");
//        $result = $aop->execute($request);
//        $responseNode = str_replace(".", "_", $request->getApiMethodName()) . "_response";
//        $resultCode = $result->$responseNode->code;
//        if(!empty($resultCode) && $resultCode == 10000){
//            // 我的信息
//            $user_info = Db::table('up_u_user')
//                ->field('user_invite_code')
//                ->where('user_id', $info['withdraw_user_id'])
//                ->find();
//            Db::startTrans();
//            try{
//                // 修改提现订单状态和审核时间
//                Db::table('up_withdraw')
//                    ->where('withdraw_id', $info['withdraw_id'])
//                    ->update([
//                        'withdraw_status' => 2,
//                        'withdraw_att_time' => date('Y-m-d H:i:s')
//                    ]);
//
//                // 插入Order表
//                $order = [
//                    'order_type' => 5,
//                    'order_price' => $info['withdraw_money'],
//                    'order_time' => date('Y-m-d H:i:s'),
//                    'order_user_id' => $info['withdraw_user_id'],
//                ];
//                Db::table('up_order')->insert($order);
//
//                //========= 教师收益
//                if(!empty($user_info['user_invite_code'])){
//                    // 邀请我的老师
//                    $invite_me_teacher = Db::table('up_u_user')
//                        ->field('user_id, user_status')
//                        ->where('user_my_code', $user_info['user_invite_code'])
//                        ->find();
//                    $allow = [1, 2, 3, 6];
//                    if($invite_me_teacher && in_array($invite_me_teacher['user_status'], $allow)){
//                        // 收益比例
//                        $rebates = Db::table('up_about')->where('about_id', 15)->value('about_rebates');
//                        // 收益金额
//                        $rebates = $info['withdraw_money'] * $rebates * 0.01;
//
//                        // 增加邀请老师的余额
//                        Db::table('up_u_user')
//                            ->where('user_id', $invite_me_teacher['user_id'])
//                            ->setInc('user_balance', $rebates);
//                        // 插入收益表
//                        $ear = [
//                            'ear_invite_user_id' => $invite_me_teacher['user_id'],
//                            'ear_by_invite_user_id' => $info['withdraw_user_id'],
//                            'ear_num' => $rebates,
//                            'ear_time' => date('Y-m-d H:i:s')
//                        ];
//                        Db::table('up_ear')->insert($ear);
//                    }
//                }
//
//                Db::commit();
//                return json(['code' => 200, 'msg' => '操作成功']);
//            }catch(\Exception $e){
//                Db::rollback();
//                return json(['code' => 100, 'msg' => '操作数据库失败']);
//            }
//        }else{
//            // $result->$responseNode->sub_msg 这个参数 是返回的错误信息
//            // throw new Exception($result->$responseNode->sub_msg);
//            return json(['code' => 100, 'msg' => $result->$responseNode->sub_msg]);
//        }
//    }
    //=============================  支付宝提现   end  ======================//
    
    /**
     * 拒绝
     * @return \think\response\Json
     */
    public function refuse(){
        $ids = input('id');
        $info = Db::table('up_withdraw')
            ->field('withdraw_money, withdraw_user_id')
            ->where('withdraw_id', $ids)
            ->find();
        Db::startTrans();
        try{
            // 改变提现申请状态
            Db::table('up_withdraw')->where('withdraw_id', $ids)->setField('withdraw_status', 3);
            
            // 恢复用户被扣除的金额
            Db::table('up_u_user')->where('user_id', $info['withdraw_user_id'])->setInc('user_balance', $info['withdraw_money']);
            Db::commit();
            return json(['code' => 200, 'msg' => '操作成功']);
        }catch(\Exception $e){
            Db::rollback();
            return json(['code' => 100, 'msg' => '操作失败']);
        }
    }
}